package com.alex.megacj.filter;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.core.io.Resource;

import com.alex.megacj.handler.RequestContext;
import com.alex.megacj.utils.CommonUtils;

public class AddTopBannerFilter extends AbstractMatchingContentFilter {

	private static final Pattern BODY_START_PATTERN = Pattern.compile("<body[^>]*>", Pattern.CASE_INSENSITIVE);
	
	private String topBanner;
	
	public void setTopBanner(Resource topBanner) throws IOException {
		this.topBanner = CommonUtils.toString(topBanner);
	}
	
	@Override
	public String filterContent(String page, RequestContext context) {
		Matcher matcher = BODY_START_PATTERN.matcher(page);
		if (matcher.find()) {
			page = page.substring(0, matcher.end()) + topBanner + page.substring(matcher.end());
		}
		return page;
	}

}
